<template>
  <div>
    <div v-if='beijing'>
      <div class="beijing" @click="close"></div>
      <div class="beijingNo">
        <div class="beijingNo0" @click="close">X</div>
        <div class="beijingNo1"></div>
        <div class="beijingNo2">您的芸券不足!</div>
        <div class="beijingNo3" @click="$router.push({path:'/getcoupon'})">查看芸券获得方式</div>
      </div>
    </div>

    <div class="exchange whiteBg">
      <div class="exchange_hd" v-if="!surplusnum">
        <span class="left"><img :src="couponParam.usrPicUrl">{{couponParam.usrName}}</span>
        <span class="right">剩余{{couponParam.sellNum}}张</span>
      </div>
      <div class="exchange_hd" v-if="surplusnum">
        <span class="left"><img :src="couponParam.mchtLogUrl"/>{{couponParam.mchtName}}</span>
        <span class="right">剩余{{surplusnum}}张</span>
      </div>
      <div class="cash_coupon">
        <div class="coupon_price right" v-if="couponParam.promAppro!='buy'">
          <span>{{price}}</span>芸券
        </div>
        <div class="coupon_price right" v-if="couponParam.promAppro=='buy'">
          <span>{{couponParam.cash}}</span>元
        </div>
        <div class="cash_coupon_info">
          <div class="cash_coupon_top">
            <div class="couponDiv">
              <coupon-denomination :item="couponParam"></coupon-denomination>
            </div>
            <div class="card_info">
              <div class="card_name">{{couponParam.couponName}}</div>
              <div class="coupon_info_item">
                <star :couponComScore="couponParam.comScore"></star>
                <p class="info_pad">{{couponParam.comNum}}条</p>
              </div>
            </div>
            <div class="clear"></div>
          </div>

          <div class="cash_coupon_sell">
            <span><img v-if="couponParam.promAppro=='buy'" style="width: 1rem;height: 1rem;"
                       src="../../images/cashIcon.png"/></span>
            <span :class="{'goleft':couponParam.promAppro=='buy'&&couponParam.couponTypes=='third'}"><img
                v-if="couponParam.couponTypes=='third'" style="width: 1rem;height: 1rem;"
                src="../../images/dui.png"/></span>
            <span>已售出   {{couponParam.soldnum}}</span>
            <span>已使用   {{couponParam.usednum}}</span>
            <div class="clear"></div>
          </div>
        </div>
        <div class="clear"></div>
      </div>
      <div class="coupon_dtl_tit">使用须知</div>
      <div class="coupon_dtl_instr">
        <ul>
          <li v-if="scpoe"><span>{{scpoe + extra}}</span></li>
          <li>
            <span>有效期{{couponParam.validatyBegin | strDate(3)}}至{{couponParam.validatyEnd | strDate(3)}}</span>
          </li>
          <li v-if="couponParam.disableDate"><span>{{couponParam.disableDate | businessDay}}不可以使用</span></li>
          <li><span>使用时间：{{userTime | timeAnalysis}}</span></li>
          <li v-if="couponParam.restricted"><span>满{{couponParam.restricted}}元可使用</span></li>
        </ul>
      </div>
      <div class="coupon_dtl_instr2">
        <ul>
          <li v-if="diejia"><i class="iconfont icon-kediejiashiyong-"></i>可叠加使用{{couponParam.useNum}}张</li>
          <li v-if="gongtong"><i class="iconfont icon-keyuqitadianziquangongtongshiyong-"></i>可与其他电子券同时使用</li>
          <li><i class="iconfont icon-buzhaolingbuduixian-"></i>不找零不兑现</li>
        </ul>
      </div>
    </div>
    <div class="gap"></div>
    <div v-if="!$route.query.buy" class="whiteBg exchange_two exchange_mar">
      <div class="exchange_num" style="border: none;">
        <span>兑换数量</span>
        <div class="exchange_num_cg right">
          <span @click="reduce()">-</span>
          <input type="number" v-model="exchangeNum">
          <span @click="add()">+</span>
        </div>
      </div>
    </div>
    <div v-if="!$route.query.buy" class="whiteBg card_exchange" @click="showCouponBox">
      <span>用券参与兑换</span>
      <i class="icon iconfont icon-right"></i>
    </div>
    <div class="warnInfo" v-show="warnShow">
      小主, 芸券不足啦! 当前账户{{myAccount}}芸券, <span @click="$router.push({path:'/getcoupon'})">芸券获得方式?</span>
    </div>
    <div class="exchange_btn">
      <!--普通券-->
      <div v-if="!$route.query.buy">
        <a v-if="exchangeState" href="javascript:;" @click="exchangeBtn" class="btn_sure right">确定兑换</a>
        <a v-if="!exchangeState" href="javascript:;" class="btn_sure right btn_gray">确定兑换</a>
      </div>
      <!--      现金券购买-->
      <a v-if="$route.query.buy" href="javascript:;" @click="exchangeBtn_new" class="btn_sure right">确定购买</a>
      <div class="total">
        <p class="total_all" v-if="!$route.query.buy">合计：<span><span>{{price * exchangeNum || 0}}</span> 芸券</span></p>
        <p class="total_all" v-if="$route.query.buy">合计：<span><span>{{couponParam.cash || 0}}</span> 元</span></p>
      </div>
    </div>
    <useCardExchange v-if="couponBox" @isBack="turnOff()" :buyCardInfo="buyCardInfo" :tlrNo='tlrNo'
                     :scanState='scanState' :inputAmt='inputAmt' :inputNoSlae='inputNoSlae'
                     :inputDeskNum='inputDeskNum'></useCardExchange>


  </div>
</template>
<script>
  import star from '../../componentes/global/star.vue'
  import * as types from '../../vuex/types.js'
  import getData from '../../service/getData.js'
  import {mapState} from 'vuex'
  import {Toast, Indicator} from 'mint-ui'
  import getData4 from '../../service/getData4.js'
  import useCardExchange from '../../componentes/global/useCardExchange.vue'
  import {Storage} from 'src/utils/storage.js'

  export default {
    components: {
      star,
      useCardExchange
    },
    data() {
      return {
        exchangeNum: 1,
        diejia: '',
        warnShow: false,
        gongtong: '',
        userTime: '',
        mcht: {mchtSearch: {}},
        param: {},
        couponParam: {},//
        myValuation: '',//小云出售价格
        price: '',//单价
        extra: '',
        scpoe: "",
        myAccount: '',
        exchangeState: true,
        couponBox: false,
        jump: true,
        allPayNum: '',
        buyCardInfo: {},
        surplusnum: '',
        tlrNo: this.$route.query.tlrNo,
        scanState: this.$route.query.scanState,
        inputAmt: this.$route.query.inputAmt,
        inputNoSlae: this.$route.query.inputNoSlae,
        inputDeskNum: this.$route.query.inputDeskNum,
        beijing: false
      }
    },

    beforeRouteLeave(to, from, next) {
      next()
    },
    created: function () {
      this.$store.commit('changeState', true);
      let me = this;
      //电子券详情
      var route = this.$route.query,
        store = Storage.get("couponInfo");
      me.surplusnum = this.$route.query.surplusnum
      me.param = {
        couponId: store.couponId || route.c,
        mchtId: store.mchtId.toString() || route.m,
        seqNo: store.id || store.seqNo || route.s || '',
        usrId: store.usrId || store.sellUsr || route.u || '',
        usrPicId: store.usrPicId || route.ui || 0
      };
      //（小云挂单）计算价格
      if (me.param.usrId == 1) {
        me.myValuation = ' ';//防止计算缓慢
        getData.computePrice({
          method: 'post',
          mchtId: me.param.mchtId,
          couponId: me.param.couponId
        }).then(rep => {
          me.myValuation = parseInt(rep.content.valuation);
          me.price = parseInt(rep.content.valuation);
        })
      }
      getData4.getDishType({mchtId: me.param.mchtId}).then(data => {
        var scpoeList = data.content.lowTypeNameList

        getData.getCouponInfo({
          "method": 'post',
          data: {
            "couponId": me.param.couponId,
            "mchtId": me.param.mchtId,
            "seqNo": me.param.seqNo,
            "usrId": me.param.usrId,
            "usrPicId": me.param.usrPicId
          }
        }).then(rep => {
          rep.content.couponId = me.param.couponId;
          me.couponParam = rep.content;

          if (rep.content) {
            me.$emit('header-info', {
              title: rep.content.couponName,
              isBack: true,
              isMessage: false
            })
            me.diejia = rep.content.useRule.indexOf("M") >= 0;
            me.gongtong = rep.content.useRule.indexOf("D") >= 0;
            // me.userTime = rep.content.useTime.split(",").join(" ");
            me.userTime = rep.content.useTime;
            if (me.param.usrId != 1) {
              me.price = me.couponParam.valuation;
            }
            if (rep.content.scpoe.indexOf("T") >= 0) {
              me.extra = "不可用"
            } else {
              me.extra = "可用"
            }

            //获取商户可用或非可用菜类列表
            let scpoe = rep.content.scpoe.substr(1, rep.content.scpoe.length + 1).split(",")
            let type = [];
            scpoe.find(data => {
              scpoeList.forEach(value => {
                if (value.typeId == data) {
                  type.push(value.typeName);
                }
              })
              me.scpoe = type.join("、")
            })
          }
        })
      });
      getData.myAccount({}, me.userInfo.usrId).then(function (rep) {
        if (rep.respCode == '00') {
          me.myAccount = rep.content
        }
      })

    },
    watch: {},
    computed: {
      ...mapState({
        setOwnerInfo: state => state.coupon.setOwnerInfo,
        couponDetail: state => state.coupon.couponDetail,
        userInfo: state => state.user.userInfo
      })
    },
    filters: {
      timeAnalysis: function (value) {
        if (!value) {
          return;
        }
        if (value.indexOf('null') > 0) {
          value = value.substring(0, value.indexOf(','));
        }
        return value
      }
    },
    methods: {
      //控制couponBox的弹出
      turnOff() {
        this.couponBox = false;
      },
      showCouponBox() {
        if (this.jump) {
          this.couponBox = true;
          this.jump = false;
          this.allPayNum = this.price * this.exchangeNum;
        } else {
          this.couponBox = true;
          this.jump = true;
          this.allPayNum = this.price * this.exchangeNum;
        }
        this.buyCardInfo = {
          couponId: this.param.couponId,
          buyCardNum: this.exchangeNum,
          ownerId: this.param.usrId,
          seqNo: this.param.seqNo,
          allPayNum: this.allPayNum,
          buyCardMchtId: this.param.mchtId,
          pathType: 'coupon'
        }
      },

      add: function () {
        if (this.exchangeNum < this.couponParam.sellNum) {
          this.exchangeNum++;
        }
        if (Number(this.myAccount) < Number(this.myValuation * this.exchangeNum)) this.warnShow = true
      },
      reduce: function () {
        if (this.exchangeNum >= 2) {
          this.exchangeNum--;
        }
        if (Number(this.myAccount) > Number(this.myValuation * this.exchangeNum)) this.warnShow = false
      },
      //普通兑换购券
      exchangeBtn: function () {
        let me = this;
        if (me.myValuation && typeof me.myValuation != 'number') {
          Toast({
            message: '价格计算中，请稍等',
            duration: 1000
          });
          return
        }
        if (this.exchangeNum > this.couponParam.sellNum) {
          Toast({
            message: '购买张数大于出售张数',
            duration: 1000
          });
          return
        }
        if (this.exchangeNum <= 0) {
          Toast({
            message: '请正确输入购买张数',
            duration: 1000
          });
          return
        }
        if (this.myAccount < this.price * this.exchangeNum) {
          this.beijing = true
          return
        }
        // Indicator.open('加载中...');
        this.$store.commit('changeState', true)
        this.exchangeState = false;
        getData.buyCoupon({
          'method': 'post',
          data: {
            couponId: me.couponParam.couponId,
            "exchangeCoupon": {
              "ecCouponId": '',//用此券去兑换，此券的id
              "ecMchtId": '',//用此券去兑换，此券的商户id
              "ecNum": '',//用此券去兑换，用了几张此券
              "ecYunCur": '',//用此券去兑换，此券估值*张数-手续费
            },
            mchtId: me.couponParam.mchtId,
            seqNo: me.couponParam.seqNo,
            num: me.exchangeNum,
            owner: me.couponParam.usrId,
            yunCur: me.price
            // "couponId": this.buyCardInfo.couponId,//要买的优惠券Id
          }
        }, me.userInfo.usrId).then(rep => {
          if (rep.respCode == '00') {
            this.exCardInfo = {
              theShow: '',
              paySum: 0,
              cardValuetion: 0,
              useCardNum: 0,
              denomination: 0,
              type: '',
              name: '',
            };
            this.$router.push({
              name: 'exchangeSuccess',
              query: {
                exCardInfo: this.exCardInfo,
                scanState: this.$route.query.scanState,
                tlrNo: this.$route.query.tlrNo,
                inputAmt: this.$route.query.inputAmt,
                inputNoSlae: this.$route.query.inputNoSlae,
                inputDeskNum: this.$route.query.inputDeskNum
              }
            });
          } else {
            this.exchangeState = true;
            Toast({
              message: rep.errorInfo,
              duration: 1000
            });
          }
        }).catch(rep => {
          this.exchangeState = true;
          Toast({
            message: '服务器异常',
            duration: 1000
          });

        })
      },
//           芸券	购券

      exchangeBtn_new: function () {

        var me = this
        me.$store.commit('changeState', true)
        me.exchangeState = false;
        getData.buyCoupons({
          'method': 'post', data: {
            amount: me.couponParam.cash,
            couponId: me.couponParam.couponId,
            mchtId: me.couponParam.mchtId,
            num: 1,
            usrId: me.userInfo.usrId,
            patterns: 'wechat'
          }
        }).then(function (rep) {
          if (rep.respCode == '00') {
            Storage.set("hasPayOrder", {
              payNum: me.couponParam.cash,
              orderId: rep.content.orderId,
              mchtId: me.couponParam.mchtId,
              couponNoInfo: "",
              market: 0,
              market2: 0,
              buyState: true
            })
            location.href = rep.content.payUrl
          } else if (rep.respCode == '01') {
            // Indicator.close();
//                      me.exchangeState=true;
            Toast({
              message: rep.errorInfo,
              duration: 1000
            });

          }
        })


      },
      close() {
        this.beijing = false
      }
    }
  }
</script>
<style scoped>
  .warnInfo {
    padding: .2rem;
    font-size: .9rem;
    text-align: center;
    position: fixed;
    bottom: 3.2rem;
    width: 100%;
    background: #fce7f0;
  }

  .warnInfo span {
    color: #ed5f94;
    text-decoration: underline;
  }

  .exchange .cash_coupon {
    width: 95%;
    height: 8rem;
  }

  .btn_gray {
    background: #999;
  }

  .goleft {
    margin-left: -2rem;
  }

  .exchange_mar {
    margin-bottom: .7rem;
  }

  .card_exchange i {
    position: absolute;
    right: .667rem;
  }

  .card_exchange {
    margin-bottom: 6rem;
    height: 3.6rem;
    font-size: .85rem;
    color: #333;
    border-top: 1px solid #f1f1f1;
    padding: 0 .667rem;
    line-height: 3.6rem;
  }

  .beijing {
    position: absolute;
    width: 100%;
    height: 100%;
    background: gray;
    left: 0;
    top: 0;
    z-index: 55;
    opacity: .7;
  }

  .beijingNo {
    width: 18rem;
    height: 13rem;
    background: #fff;
    z-index: 77;
    position: absolute;
    left: 20%;
    top: 15rem;
  }

  .beijingNo1 {
    width: 5rem;
    height: 5rem;
    margin-left: 6rem;
    margin-top: 2rem;
    background: url(../../images/No1.png) no-repeat left top;
    background-size: cover;
  }

  .beijingNo0 {
    position: absolute;
    right: 1rem;
    top: 1rem;
  }

  .beijingNo2 {
    height: 4rem;
    line-height: 4rem;
    text-align: center;
  }

  .beijingNo3 {
    text-decoration: underline;
    text-align: center;
    color: #ee5088;
  }
</style>
